package wangxiaotao.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import wangxiaotao.controller.BaseController;
import wangxiaotao.shiro.common.SerializeUtils;


import java.time.Duration;

/**
 * redis配置
 */
@Configuration
public class RedisConfig {

    /**
     * 序列化设置 使用Jackson
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //将工厂设置到模板中
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值

        //key序列化方式  使用StringRedisSerializer来序列化key
        template.setKeySerializer(new StringRedisSerializer());//默认为StandardCharsets.UTF_8
        template.setHashKeySerializer(new SerializeUtils());
        //value序列化
        template.setValueSerializer(new SerializeUtils());
        //value hashmap的序列化
        template.setHashValueSerializer(new SerializeUtils());

        return template;
    }
    public RedisSerializer<Object> Jackson2Serializer(){
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        //ObjectMapper可以从字符串、流或文件解析JSON，并创建Java对象或对象图来表示已解析的JSON。
        // 将JSON解析为Java对象也称为从JSON反序列化Java对象 //json转对象类，不设置默认的会将json转成hashmap
        ObjectMapper om = new ObjectMapper();
        //PropertyAccessor:设置类中哪些方法或者属性被序列化 ALL:表示所有访问器都受到影响。
        //JsonAutoDetect.Visibility：设置哪些修饰的可以被序列化 ANY:类型的访问修饰符都是可以接受的，从私有到公共。
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //指定序列化输入类型 反序列化的支持
        om.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,// 对所有非final类型或者非final类型元素的数组。
                JsonTypeInfo.As.WRAPPER_OBJECT);
        //设置自定义的序列化和反序列化的标准 也就是ObjectMapper
        serializer.setObjectMapper(om);
        return serializer;
    }

    @Bean//连接池
    public LettuceConnectionFactory connectionFactory(){
        return new LettuceConnectionFactory();
    }


    /**
     * 缓存的key生成器
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator(){
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(method.getName()).append(":");
            try {
                long current = ((BaseController) target).getPage().getCurrent();
                long size = ((BaseController) target).getPage().getSize();
                sb.append(current).append(":");
                sb.append(size).append(":");
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    /**
     * 缓存配置
     * @param factory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1))  // 设置缓存有效期一小时
                .disableCachingNullValues()
//                .computePrefixWith(cacheName -> "yourAppName".concat(":").concat(cacheName).concat(":"))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new SerializeUtils()));

        return RedisCacheManager.builder(factory)
                .cacheDefaults(cacheConfiguration)
                .build();
    }

    /**
     * 过期监听
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}
